<template>
  <div class="app-container calendar-list-container">
    <!-- filter 条件查询 -->
    <div class="filter-container">
      <div style="display:inline-block;font-size:15px;">医院名称：</div>
      <el-input
        clearable
        @keyup.enter.native="handleFilter"
        v-model="listQuery.hospitalName"
        style="width: 200px;margin-right:15px;margin-top:7px"
        class="filter-item"
        placeholder="请输入医院名称"
      ></el-input>
      <div style="display:inline-block;font-size:15px;">详细地址：</div>
      <el-input
        clearable
        @keyup.enter.native="handleFilter"
        v-model="listQuery.showAddress"
        style="width: 200px;margin-right:15px;margin-top:7px"
        class="filter-item"
        placeholder="请输入详细地址"
      ></el-input>
      <div style="display:inline-block;font-size:15px;">管理员姓名：</div>
      <el-input
        clearable
        @keyup.enter.native="handleFilter"
        v-model="listQuery.managerName"
        style="width: 200px;margin-right:15px;margin-top:7px"
        class="filter-item"
        placeholder="请输入管理员姓名"
      ></el-input>
      <div style="display:inline-block;font-size:15px;">管理员手机号：</div>
      <el-input
        clearable
        @keyup.enter.native="handleFilter"
        v-model="listQuery.managerPhone"
        style="width: 200px;margin-right:15px;margin-top:7px"
        class="filter-item"
        placeholder="请输入管理员手机号"
      ></el-input>
      <el-button
        class="filter-item"
        type="primary"
        v-waves
        icon="el-icon-search"
        @click="handleFilter"
        style="width: 80px;margin-top:7px"
      >搜索</el-button>
      <el-button
        type="primary"
        class="filter-item"
        @click="handleDownload"
        icon="el-icon-download"
        :loading="downloadLoading"
        style="width: 120px;margin-top:7px"
      >批量导出</el-button>
      <el-button
        type="primary"
        class="filter-item"
        @click="dialog.upload = true"
        icon="el-icon-download"
        :loading="uploadLoading"
        style="width: 120px;margin-right:10px;margin-top:7px"
      >批量导入</el-button>
      <router-link :to="{name:'hospital_add'}">
        <el-button
          class="filter-item"
          style="width: 80px;margin-right:10px;margin-top:7px"
          icon="el-icon-circle-plus-outline"
          @click="addHospitalBtn"
          v-waves
          type="primary"
        >新增</el-button>
      </router-link>
    </div>
    <!-- table 表格 -->
    <el-table
      :data="list"
      v-loading="loading.list"
      element-loading-text="给我一点时间"
      border
      fit
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column align="center" label="序号" prop="index" width="50"/>
      <el-table-column align="center" label="医院名称" prop="hospitalName"/>
      <el-table-column align="center" label="详细地址" prop="showAddress"/>
      <el-table-column align="center" label="管理员姓名" prop="managerName"/>
      <el-table-column align="center" label="管理员手机号" prop="managerPhone"/>
      <el-table-column align="center" label="押金" prop="deposit"/>
      <el-table-column align="center" label="陪护床数量" prop="num"/>
      <el-table-column
        align="center"
        label="收费规则"
        class-name="small-padding fixed-width"
        width="400"
      >
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="small"
            @click="editPackage(1,scope.row.hospitalId,scope.row.hourPrice)"
          >按小时</el-button>
          <el-button
            type="danger"
            size="small"
            @click="OverTimePriceBtn(scope.row.hospitalId,scope.row.overTimePrice)"
           
          >超时价格</el-button>
          <el-button
            type="success"
            size="small"
            @click="editPackage(2,scope.row.hospitalId,'',scope.row.overTimePrice)"
          >按时间段</el-button>
          <el-button
            type="warning"
            size="small"
            @click="editPackage(3,scope.row.hospitalId,'',scope.row.overTimePrice)"
          >按天</el-button>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" class-name="small-padding fixed-width" width="250">
        <template slot-scope="scope">
          <el-button
            type="danger"
            size="small"
            v-if="scope.row.num == 0"
            @click="delHospital(scope.row.hospitalId)"
          >删除</el-button>
          <el-button
            type="warning"
            size="small"
            v-if="scope.row.managerName"
            @click="unBinds(scope.row.hospitalId)"
          >解绑</el-button>
          <router-link :to="{name:'hospital_detail', query: {hospitalId: scope.row.hospitalId}}">
            <el-button type="primary"  style="margin-left:8px;" size="small">编辑</el-button>
          </router-link>
        </template>
      </el-table-column>
    </el-table>
    <!-- pagination 分页 -->
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="listQuery.offset"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="listQuery.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>
    <!-- 收费规则 弹窗 -->
    <el-dialog title="收费规则" :visible.sync="dialogFormVisible" width="45%">
      <!-- 小时套餐 -->
      <div
        v-show="editRuleForm.ruleType == 1"
        style="border:1px solid #dedede;border-radius:6px;padding:10px 15px 20px;margin-top:15px;"
      >
        <div style="font-size:15px;margin-right:12px;margin-bottom:10px;">按小时收费：</div>
        <div style="display:inline-block;font-size:15px;margin-right:12px;">小时计费：</div>
        <el-input-number
          clearable
          :precision="2"
          :step="0.01"
          :min="0.01"
          v-model="editRuleForm.rulePrice"
          style="dispaly:inline-block;font-size:15px;margin-right:15px;width:150px;"
        ></el-input-number>
        <div style="display:inline-block;font-size:15px;margin-right:12px;">元/小时</div>
      </div>
      <!-- 时间段套餐 -->
      <div
        v-show="editRuleForm.ruleType == 2"
        style="border:1px solid #dedede;border-radius:6px;padding:10px 15px 20px;margin-top:15px;"
      >
        <div style="display:inline-block;font-size:15px;margin-right:12px;">时间段收费：</div>
        <el-button
          class="filter-item"
          style="width: 80px;margin-right:10px;margin-top:7px"
          icon="el-icon-circle-plus-outline"
          v-waves
          type="primary"
          @click="addTimes"
        >添加</el-button>
        <el-table
          :data="ruleTypeNotes"
          v-loading="loading.list1"
          element-loading-text="给我一点时间"
          border
          fit
          highlight-current-row
          style="width: 100%;margin-top:15px;margin-bottom:15px;"
        >
          <el-table-column align="center" label="序号" prop="index" width="50"/>
          <el-table-column align="center" label="时间段" prop="startTime">
            <template slot-scope="scope">
              {{scope.row.openStartTime}}
              <br>至
              <br>
              {{scope.row.closeEndTime}}
            </template>
          </el-table-column>
          <el-table-column align="center" label="金额" prop="rulePrice"/>
          <el-table-column
            align="center"
            label="操作"
            class-name="small-padding fixed-width"
            width="250"
          >
            <template slot-scope="scope">
              <el-button type="danger" size="mini" @click="delRules(scope.row.ruleId)">删除</el-button>
              <el-button type="success" @click="getEditTimes(scope.row)">编辑</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- <div style="display:inline-block;font-size:15px;margin-right:12px;">超时计费：</div>
        <el-input clearable :min="0" v-model="editRuleForm.overTimePrice" placeholder="请输入内容" type="number" style="dispaly:inline-block;font-size:15px;margin-right:15px;width:150px;"></el-input>-->
      </div>
      <!-- 按日套餐 -->
      <div
        v-show="editRuleForm.ruleType == 3"
        style="border:1px solid #dedede;border-radius:6px;padding:10px 15px 20px;margin-top:15px;"
      >
        <div style="display:inline-block;font-size:15px;margin-right:12px;">日套餐收费：</div>
        <el-button
          class="filter-item"
          style="width: 80px;margin-right:10px;margin-top:7px"
          icon="el-icon-circle-plus-outline"
          v-waves
          type="primary"
          @click="addTimes"
        >添加</el-button>
        <el-table
          :data="ruleTypeNotes"
          v-loading="loading.list1"
          element-loading-text="给我一点时间"
          border
          fit
          highlight-current-row
          style="width: 100%;margin-top:15px;margin-bottom:15px;"
        >
          <el-table-column align="center" label="序号" prop="index" width="50"/>
          <el-table-column align="center" label="天数" prop="dayNumber"/>
          <el-table-column align="center" label="金额" prop="rulePrice"/>
          <el-table-column
            align="center"
            label="操作"
            class-name="small-padding fixed-width"
            width="250"
          >
            <template slot-scope="scope">
              <el-button type="danger" size="mini" @click="delRules(scope.row.ruleId)">删除</el-button>
              <el-button type="success" @click="getEditTimes(scope.row)">编辑</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- <div style="display:inline-block;font-size:15px;margin-right:12px;">超时计费：</div>
        <el-input clearable :min="0" v-model="editRuleForm.overTimePrice" placeholder="请输入内容" type="number" style="dispaly:inline-block;font-size:15px;margin-right:15px;width:150px;"></el-input>-->
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="rulesFormSubmit">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 【编辑/新增】计费标准 弹窗 -->
    <el-dialog :title="type==1?'编辑计费标准':'新增计费标准'" :visible.sync="dialogVisible" width="30%">
      <el-form
        :model="editTimes"
        :rules="editRules"
        ref="editTimes"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="选择时间段：" label-width="120px" v-if="editRuleForm.ruleType == 2">
          <el-col :span="11">
            <el-form-item prop="startTime">
              <el-time-select
                style="width:180px;"
                placeholder="起始时间"
                v-model="editTimes.startTime"
                :picker-options="{
                  start: '00:00',
                  step: '00:05',
                  end: '24:00'
                }"
              ></el-time-select>
            </el-form-item>
          </el-col>
          <el-col :span="2" style="text-align:center;">-</el-col>
          <el-col :span="11">
            <el-form-item prop="endTime">
              <el-time-select
                style="width:180px;"
                placeholder="结束时间"
                v-model="editTimes.endTime"
                :picker-options="{
                  start: '00:00',
                  step: '00:05',
                  end: '24:00'
                }"
              ></el-time-select>
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label="天数：" prop="dayNumber" label-width="120px" v-else>
          <el-input-number clearable style="width:120px;" :min="0" v-model="editTimes.dayNumber" ></el-input-number>
        </el-form-item>
        <el-form-item label="金额：" prop="rulePrice" label-width="120px">
          <el-input-number
            clearable
            style="width:120px;"
            :precision="2"
            :step="0.01"
            :min="0.01"
            v-model="editTimes.rulePrice"
          ></el-input-number>
          <span>元</span>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editTimesSubmit('editTimes')">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 设置超时费用 弹窗 -->
    <el-dialog title="设置每小时超时价格" :visible.sync="dialogVisible1" width="30%">
      <el-form
        :model="overTimeQuery"
        :rules="editRules"
        ref="overTimeForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="金额：" prop="price">
          <el-input-number
            placeholder="请输入金额"
            clearable
            style="width:180px;"
            :min="0"
            :precision="2"
            :step="0.01"
            v-model="overTimeQuery.price"
          ></el-input-number>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible1 = false">取 消</el-button>
        <el-button type="primary" @click="setOverTimePrice('editTimes')">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 导入时选择医院 弹窗 -->
    <el-dialog title="导入" :visible.sync="dialog.upload" width="500px" class="uploadDialog">
      <el-form :model="uploadQuery" ref="upload" label-position="right" label-width="120px">
        <el-form-item label="医院" prop="deptName">
          <el-select v-model="uploadQuery.hospitalId" placeholder="请选择" style="width:220px;">
            <el-option
              v-for="item in list"
              :key="item.hospitalId"
              :label="item.hospitalName"
              :value="item.hospitalId"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="loading.upload" @click="uploadBtn">确定</el-button>
        <el-button type="primary" @click="dialog.upload = false">取消</el-button>
      </div>
    </el-dialog>
    <!-- 导入excel -->
    <input type="file" @change="uploadExcel" ref="uploadExcel" style="display:none">
  </div>
</template>
<script>
import {
  getHospitalList,
  setRules,
  updateHour,
  getRules,
  delRules,
  delHospital,
  importHosExecl,
  unbind
} from "@/api/hospital";
import { parseTime, getTimeHM } from "@/utils";
import { setStorage } from "@/utils/storage";
export default {
  name: "hospital_list",
  data() {
    return {
      dialogFormVisible: false,
      dialogVisible: false,
      dialogVisible1: false,
      ruleType: 0,
      hourPrice: "",
      ruleTypeNotes: null,
      editRuleForm: {},
      editTimes: {
        startTime: "",
        endTime: "",
        dayNumber: "",
        rulePrice: ""
      },
      type: 1,
      editRules: {
        startTime: [
          {
            type: "string",
            required: true,
            message: "请选择开始时间",
            trigger: "change"
          }
        ],
        endTime: [
          {
            type: "string",
            required: true,
            message: "请选择结束时间",
            trigger: "change"
          }
        ],
        dayNumber: [
          { required: true, message: "请填写天数", trigger: "change" }
        ],
        rulePrice: [
          { required: true, message: "请填写金额", trigger: "change" }
        ],
        price: [
          { required: true, message: "请填写超时金额", trigger: "change" }
        ]
      },
      labelPosition: "right",
      total: 0,
      list: null,
      loading: {
        list: false,
        list1: false,
        upload: false
      },
      dialog: {
        charge: false,
        upload: false
      },
      listQuery: {
        offset: 1,
        limit: 10,
        hospitalId: "",
        hospitalName: "",
        showAddress: "",
        managerName: "",
        managerPhone: ""
      },
      downloadLoading: false,
      uploadLoading: false,
      uploadQuery: {
        hospitalId: ""
      },
      overTimeQuery: {
        hospitalId: "",
        type: 2,
        price: ""
      }
    };
  },
  created() {
    this.getHospitalList();
  },
  methods: {

    BlurText(e){
      let boolean = new RegExp("^[1-9][0-9]*$").test(e)
      if(!boolean){
        this.$message.error("天数请输入正整数")
        e = ''
        return false
      }
      return true
    },

    // 点击小时套餐按钮
    editPackage(type, hospitalId, hourPrice, overTimePrice) {
      if (type !== 1 && !overTimePrice) {
        this.$message({
          showClose: true,
          message: "请先设置每小时超时价格",
          type: "warning"
        });
        return;
      }
      this.dialogFormVisible = true;
      this.editRuleForm.ruleType = type;
      if (type == 1 && hourPrice) {
        this.editRuleForm.rulePrice = hourPrice;
      }
      this.editRuleForm.hospitalId = hospitalId;
      if (type !== 1) this.getRules();
    },
    // 弹出收费规则弹框
    getRuleDialog(hospitalId, ruleType) {
      this.editRuleForm.hospitalId = hospitalId;
      this.editRuleForm.ruleType = ruleType;
      this.getRules();
      this.dialogFormVisible = true;
    },
    // 获取天数和时间段套餐
    async getRules() {
      this.loading.list1 = true;
      const data = await getRules({
        hospitalId: this.editRuleForm.hospitalId,
        ruleType: this.editRuleForm.ruleType
      });
      if (data.code == 1) {
        this.ruleTypeNotes = data.data.map((item, index) => ({
          ...item,
          index: index + 1,
          openStartTime: item.openStartTime
            ? item.openStartTime.split(" ")[1]
            : "",
          closeEndTime: item.closeEndTime ? item.closeEndTime.split(" ")[1] : ""
        }));
      }
      this.loading.list1 = false;
    },
    // 确定按钮--收费规则弹框确定按钮
    async rulesFormSubmit() {
      if (this.editRuleForm.ruleType == 1) {
        // 小时套餐
        const data = await updateHour({
          hospitalId: this.editRuleForm.hospitalId,
          type: 1,
          price: this.editRuleForm.rulePrice
        });
        if (data.code == 1) {
          this.$message({
            showClose: true,
            message: "操作成功！",
            type: "success"
          });
          this.editRuleForm = {};
          this.dialogFormVisible = false;
          this.getHospitalList();
        }
      } else {
        this.dialogFormVisible = false;
      }
    },
    // 删除时间套餐
    async delRules(ruleId) {
      const data = await delRules({
        ruleId
      });
      if (data.code == 1) {
        this.getRules();
      }
    },
    // 编辑按钮--时间套餐的编辑按钮
    async getEditTimes(obj) {
      this.type = 1;
      if (obj.ruleType == 2) {
        // 时间段套餐
        this.editTimes.startTime = obj.openStartTime;
        this.editTimes.endTime = obj.closeEndTime;
      } else {
        
        // 日套餐
        this.editTimes.dayNumber = obj.dayNumber;
      }
      this.editRuleForm.ruleId = obj.ruleId;
      this.editTimes.rulePrice = obj.rulePrice;
      this.dialogVisible = true;
    },
    // 添加按钮--添加套餐（时间段和日套餐）
    addTimes() {
      this.editTimes = {};
      this.type = 2;
      this.dialogVisible = true;
    },
    //【编辑/新增】时间套餐确定按钮
    async editTimesSubmit(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          var obj = {
            ruleId: this.type == 1 ? this.editRuleForm.ruleId : "",
            hospitalId: this.editRuleForm.hospitalId,
            ruleType: this.editRuleForm.ruleType,
            rulePrice: this.editTimes.rulePrice
          };
          if (this.editRuleForm.ruleType == 2) {
            (obj.startTime = "2018-01-01 " + this.editTimes.startTime + ":00"),
              (obj.endTime = "2018-01-01 " + this.editTimes.endTime + ":00");
          } else {
            const aa = this.BlurText(this.editTimes.dayNumber);
            if(!aa) {
              return
            }
            obj.dayNumber = this.editTimes.dayNumber;
          }
          const data = await setRules(obj);
          if (data.code == 1) {
            this.dialogVisible = false;
            this.getRules();
            this.$refs["editRules"].resetFields();
          }
        } else {
          // console.log("error submit!!");
          return false;
        }
      });
    },
    // 设置超时费用按钮
    OverTimePriceBtn(hospitalId, overTimePrice) {
      this.dialogVisible1 = true;
      this.overTimeQuery.hospitalId = hospitalId;
      this.overTimeQuery.price = overTimePrice;
      this.overTimeQuery.type=2;//超时传2
    },
    // 确定按钮--设置超时费用
    async setOverTimePrice() {
      this.$refs["overTimeForm"].validate(async valid => {
        if (valid) {
          const data = await updateHour(this.overTimeQuery);
          if (data.code == 1) {
            this.$message({
              showClose: true,
              message: "操作成功！",
              type: "success"
            });
            this.overTimeQuery = {};
            this.dialogVisible1 = false;
            this.getHospitalList();
            this.$refs["overTimeForm"].resetFields();
          }
        } else {
          // console.log("error submit!!");
          return false;
        }
      });
    },
    // 去编辑页面
    toEdit(nowHospitalNotes) {
      setStorage("nowHospitalNotes", nowHospitalNotes);
      this.$router.push({ name: "hospital_detail" });
    },
    
    //导出
    handleDownload() {
      this.downloadLoading = true;
      import("@/vendor/Export2Excel").then(excel => {
        const tHeader = [
          "医院名称",
          "详细地址",
          "管理员姓名",
          "管理员手机号",
          "押金",
          "超时费用",
          "陪护床数量"
        ];
        const filterVal = [
          "hospitalName",
          "showAddress",
          "managerName",
          "managerPhone",
          "deposit",
          "overTimePrice",
          "num"
        ];
        const data = this.formatJson(filterVal, this.list);
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: "医院列表"
        });
        this.downloadLoading = false;
      });
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v =>
        filterVal.map(j => {
          if (j === "ruleType") {
            return v[j] == 1
              ? "按小时计费"
              : v[j] == 2
              ? "按时间段计费"
              : "按日套餐计费";
          } else if (j === "isPlatform") {
            return v[j] == 1 ? "医院代理" : "平台直营";
          } else {
            return v[j];
          }
        })
      );
    },
    uploadBtn() {
      this.$refs.uploadExcel.click();
    },
    //导入
    async uploadExcel(e) {
      this.dialog.upload = true;
      try {
        const excel = e.target.files[0];
        const fd = new FormData();
        fd.append("file", excel);
        fd.append("hospitalId", this.uploadQuery.hospitalId);
        const data = await importHosExecl(fd);
        if (data.code == 1) {
          this.$message.success("导入成功");
          this.getHospitalList();
        } else {
          this.$message.error(res.data.msg);
        }
      } catch (error) {
        this.$refs.uploadExcel.value = "";
        this.dialog.upload = false;
      }
      this.dialog.upload = false;
      this.$refs.uploadExcel.value = "";
    },
    // 获取医院列表
    async getHospitalList() {
      this.loading.list = true;
      const data = await getHospitalList(this.listQuery);
      if (data.code == 1) {
        this.list = data.data.records.map((item, index) => ({
          index: index + 1,
          ...item
        }));
        this.total = data.data.total;
        this.loading.list = false;
      }
    },
    // 解绑
    async unBinds(hospitalId) {
      this.$confirm("解绑后此医院所有收益均为总平台所有, 是否继续?", "提示", 
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
      ).then(async () => {
          const  data  = await unbind({ hospitalId });
          if (data.code == 1) {
            this.$message.success("解绑成功");
          } else {
            this.$message.error(data.msg);
          }
          this.getHospitalList();
        })
        .catch(() => {});
    },

    // 删除医院
    async delHospital(hospitalId) {
      this.$confirm(
        "删除医院后会将该医院下所有的科室、病房以及床号都删除",
        "是否确认删除？",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消"
        }
      ).then(async () => {
        try {
          const data = await delHospital({ hospitalId });
          if (data.code == 1) {
            this.$message({
              type: "success",
              message: "删除成功"
            });
            this.getHospitalList();
          }
        } catch (error) {}
      });
    },
    // 去往新增医院
    addHospitalBtn() {
      this.$router.push({ name: "hospital_add" });
    },
    handleFilter() {
      this.listQuery.offset = 1;
      this.getHospitalList();
    },
    handleSizeChange(val) {
      this.listQuery.limit = val;
      this.getHospitalList();
    },
    handleCurrentChange(val) {
      this.listQuery.offset = val;
      this.getHospitalList();
    }
  }
};
</script>
<style lang="scss" scoped>
/deep/ .el-form-item__label {
  text-align: left;
  font-size: 15px;
  font-weight: normal;
}
/deep/ .uploadDialog .el-form-item__label {
  text-align: right;
}
</style>

